package com.xdqzy.baseline.common.response;

import com.alibaba.fastjson.JSONObject;
import com.xdqzy.baseline.common.model.RestResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.AnnotatedElement;
import java.util.Objects;

/**
 * @author : qss
 * @version V1.0
 * @Title : 接口响应结果包装
 * @ClassName: com.xdqzy.baseline.common.model.GlobalResponseHandler.java
 * @Description:
 * @date :  2020-10-20 17:49
 */
@ControllerAdvice
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {

    /**
     * Description: 判断是否小视返回对象<br>
     *
     * @param returnType 返回类型
     * @param converterType 转换器
     * @return <br>
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        AnnotatedElement annotatedElement = returnType.getAnnotatedElement();
        CustomResponseBody customResponseBody = annotatedElement.getAnnotation(CustomResponseBody.class);
        return Objects.nonNull(customResponseBody);
    }

    /**
     * Description: 重写响应体<br>
     *
     * @param body 消息体
     * @param returnType 返回类型
     * @param selectedContentType 选择内容类型
     * @param selectedConverterType 选择转换类型
     * @param request request
     * @param response 响应
     * @return <br>
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                                  ServerHttpResponse response) {
        /**
         * 移除JsonUtil.getSucc写法 在string对象情况下存在问题
         */
        if (null == body) {
            body = new JSONObject();
        }
        return  RestResult.buildSuccess(body);
    }
}
